package org.zachary.commonservice.service.impl;

import org.springframework.stereotype.Service;
import org.zachary.commonservice.entity.*;
import org.zachary.commonservice.mapper.CreditContractRecordMapper;
import org.zachary.commonservice.service.CreditContractRecordService;

import java.util.*;

@Service
public class CreditContractRecordServiceImpl implements CreditContractRecordService {

    private final CreditContractRecordMapper mapper;

    public CreditContractRecordServiceImpl(CreditContractRecordMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public List<CreditCategoryStatsDTO> getCategoryStats() {
        return mapper.getCreditCategoryStats();
    }
    @Override
    public List<CreditCategoryStatsDTO> getCategoryStatsByCounty(String county) {
        return mapper.getCreditCategoryStatsByCounty(county);
    }

    @Override
    public Integer countAllUsers() {
        return mapper.countAllUsers();
    }
    @Override
    public double getCompletionRate() {
        CreditContractRateDTO dto = mapper.getContractRateByDescription();
        if (dto == null || dto.getTotalCount() == null || dto.getTotalCount() == 0) {
            return 0.0;
        }
        int total = dto.getTotalCount();
        int breach = dto.getBreachCount() == null ? 0 : dto.getBreachCount();
        return (total - breach) * 1.0 / total;
    }
    @Override
    public List<DimensionTopUserVO> getTopUsersByDimension() {
        List<DimensionTopUserDTO> dtoList = mapper.selectTopUsersByDimension();

        Map<String, String> titleMap = Map.of(
                "总信用分", "信用楷模",
                "信用商业", "诚信领袖",
                "信用生活", "守信模范",
                "亲社会行为", "公益先锋",
                "基本信息", "信用磐石"
        );

        // 指定维度排序
        List<String> dimensionOrder = List.of("总信用分", "信用商业", "信用生活", "亲社会行为", "基本信息");

        List<DimensionTopUserVO> result = new ArrayList<>();
        int id = 1;
        for (String dimension : dimensionOrder) {
            for (DimensionTopUserDTO dto : dtoList) {
                if (dimension.equals(dto.getDimensionType())) {
                    DimensionTopUserVO vo = new DimensionTopUserVO();
                    vo.setId(id++);
                    vo.setName(dto.getDimensionType());
                    vo.setValue(dto.getDimensionScore());
                    vo.setNickname(dto.getNickName());
                    vo.setTitle(titleMap.getOrDefault(dto.getDimensionType(), "维度之星"));
                    result.add(vo);
                    break; // 每个维度只选一条
                }
            }
        }
        return result;
    }



    @Override
    public Integer countAllUsing() {
        return mapper.countAllUsing();
    }

    @Override
    public List<CountyIncomeDTO> getIncomeByCounty() {
        return mapper.getIncomeByCounty();
    }
    @Override
    public List<DistrictScoreStatsDTO> getDistrictScoreStats() {
        List<CountyScoreDTO> all = mapper.findAllScoreWithCounty();

        Map<String, List<Integer>> districtScores = new HashMap<>();
        for (CountyScoreDTO dto : all) {
            districtScores
                    .computeIfAbsent(dto.getCounty(), k -> new ArrayList<>())
                    .add(dto.getCreditScore());
        }

        List<DistrictScoreStatsDTO> result = new ArrayList<>();
        for (Map.Entry<String, List<Integer>> entry : districtScores.entrySet()) {
            List<Integer> scores = entry.getValue();
            if (scores.isEmpty()) continue;

            Collections.sort(scores);
            int size = scores.size();
            result.add(new DistrictScoreStatsDTO(
                    entry.getKey(),
                    scores.get(0),
                    getPercentile(scores, 25),
                    getPercentile(scores, 50),
                    getPercentile(scores, 75),
                    scores.get(size - 1)
            ));
        }

        return result;
    }


    private int getPercentile(List<Integer> sorted, int percentile) {
        if (sorted.isEmpty()) return 0;
        double pos = percentile / 100.0 * (sorted.size() - 1);
        int lower = (int) Math.floor(pos);
        int upper = (int) Math.ceil(pos);
        return (sorted.get(lower) + sorted.get(upper)) / 2;
    }
    @Override
    public List<CreditRecordSimpleDTO> getLatestRecords() {
        return mapper.selectLatestRecords();
    }


}
